#ifndef THREADPOOL_HPP
#define THREADPOOL_HPP
#include <atomic>
#include <functional>
#include <future>
#include <queue>
#include <stdexcept>
#include <vector>

namespace std
{
const int THREADPOOL_MAX_NUM{16};
class threadpool
{
    using Task = function<void()>;
    vector<thread> _pool;
    queue<Task> _tasks;
    mutex _lock;
    condition_variable _task_cv;
    atomic<bool> _run{true};
    atomic<int> _idlThrNum{0};

public:
    inline threadpool(unsigned short size = 4)
    {
        addThread(size);
    } //TODO
    inline ~threadpool()
    {
        _run = false;
        _task_cv.notify_all();
        for (auto &th : _pool)
            if (th.joinable())
                th.join();
    }
    template <class F, class... Args>
    auto commit(F &&f, Args &&... args) -> future<decltype(f(args...))>
    {
        if (!_run)
            throw runtime_error("commit on ThreadPool is stopped.");
        using RetType = decltype(f(args...));
        auto task = make_shared<packaged_task<RetType()>>(bind(forward<F>(f), forward<Args>(args)...));
        future<RetType> future = task->get_future();
        {
            lock_guard<mutex> lock{_lock};
            _tasks.emplace([task]() { (*task)(); });
        }
#ifdef THREADPOOL_AUTO_GROW
        if (_idlThrNum < 1 && _pool.size() < THREADPOOL_MAX_NUM)
            addThread(1);
#endif
        _task_cv.notify_one();
        return future;
    }
    int idlCount() { return _idlThrNum; }
    int thrCount() { return _pool.size(); }
#ifndef THREADPOOL_AUTO_GROW
private:
#endif
    void addThread(unsigned short size)
    {
        for (; _pool.size() < THREADPOOL_MAX_NUM && size > 0; --size)
        {                               //增加线程数量,但不超过 预定义数量 THREADPOOL_MAX_NUM
            _pool.emplace_back([this] { //工作线程函数
                while (_run)
                {
                    Task task; // 获取一个待执行的 task
                    {
                        // unique_lock 相比 lock_guard 的好处是：可以随时 unlock() 和 lock()
                        unique_lock<mutex> lock{_lock};
                        _task_cv.wait(lock, [this] {
                            return !_run || !_tasks.empty();
                        }); // wait 直到有 task
                        if (!_run && _tasks.empty())
                            return;
                        task = move(_tasks.front()); // 按先进先出从队列取一个 task
                        _tasks.pop();
                    }
                    _idlThrNum--;
                    task(); //执行任务
                    _idlThrNum++;
                }
            });
            _idlThrNum++;
        }
    }
};
} // namespace std
#endif